package ext.tianma.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jfree.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import wt.log4j.LogR;
import wt.util.WTProperties;

import java.io.*;
import java.util.*;

public class PropertiesUtil {

	private static final String CLASSNAME = PropertiesUtil.class.getName();
	private static Logger logger = LogR.getLogger(CLASSNAME);
	private static final String suffix = "properties";

	private Map<String, String> hmConfig = new HashMap<String, String>();
	private long lastModifyTime = 0L;
	private File fileObj = null;
	private String filepath = "";
	private static PropertiesUtil propertiesUtil = null;
	Properties pro = new Properties();

	public Properties getProperties() {
		return this.pro;
	}

	public PropertiesUtil(String configFilePath) {
		this.filepath = configFilePath;
		readConfig(false);
	}

	/**
	 * 通过key值和路径获取value
	 * 
	 * @param
	 * @param
	 * @return
	 * @throws IOException
	 * @Exception
	 */
	public static String getValueByKey(String key, String path)
			throws IOException {
		if (checkFileName(path) && isFileExist(path)) {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(path), "utf-8"));
			Properties props = new Properties();
			props.load(br);
			String value = props.getProperty(key);
			br.close();
			if (value != null && !value.isEmpty()) {
				return value;
			}
		}
		return "";
	}

	/**
	 * 
	 * 方法名称: checkFileName 描 述 : 校验路径中的文件格式以及文件是否存在和正确
	 * 
	 * @param
	 * @param
	 * @return
	 * @Exception
	 */
	public static boolean checkFileName(String path) {
		logger.info(">>>>>>>>>>>" + CLASSNAME + "checkFileName()<<<<<<<<<<<<<");
		logger.info(">>>>>>>>>>>" + path + "<<<<<<<<<<<<<");
		if (!path.isEmpty() && path.length() > 0) {
			int index = path.lastIndexOf(".");
			String suffix_ = path.substring(index + 1, path.length());
			if (suffix.equals(suffix_) && isFileExist(path)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 方法名称: isFileExist 描 述 : 根据路径判断文件是否存在
	 * 
	 * @param
	 * @param
	 * @return
	 * @Exception
	 */
	public static boolean isFileExist(String path) {
		logger.info(">>>>>>>>>>>" + CLASSNAME + "isFileExist()<<<<<<<<<<<<<");
		logger.info(">>>>>>>>>>>" + path + "<<<<<<<<<<<<<");
		File file = new File(path);
		if (file.exists()) {
			return true;
		} else {
			Log.error(">>>>>>>>>>>" + CLASSNAME
					+ ".properties File does not exist !");
			return false;
		}
	}

	public void readConfig(boolean createFile) {
		try {
			WTProperties localPro = WTProperties.getLocalProperties();
			String wthome = localPro.getProperty("wt.home");
			fileObj = new File(wthome + File.separator + filepath);
			// 文件不存在则自动创建文件
			if (createFile) {
				File mkdirs = fileObj.getParentFile();
				if (!mkdirs.exists()) {
					mkdirs.mkdirs();
				}
				if (!fileObj.exists()) {
					fileObj.createNewFile();
				}
			}
			FileInputStream fis = new FileInputStream(fileObj/*
															 * wthome +
															 * File.separator +
															 * filepath
															 */);
			InputStreamReader isr = new InputStreamReader(fis, "utf-8");
			pro.load(isr);
			Enumeration enuPro = pro.propertyNames();
			hmConfig.clear();// 读取前清除历史
			while (enuPro.hasMoreElements()) {
				String proName = (String) enuPro.nextElement();
				String proValue = (String) pro.getProperty(proName);
				try {
					proName = new String(proName.getBytes("utf-8"), "utf-8");
					proValue = new String(proValue.getBytes("utf-8"), "utf-8");
				} catch (UnsupportedEncodingException e) {
					logger.error(e.getMessage(), e);
				}
				hmConfig.put(proName, proValue);
			}
			isr.close();
			fis.close();
			lastModifyTime = fileObj.lastModified();
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}

	public String getValueByKey(String key) {
		isUpdateFile();
		// 初始化已经处理转码，在继续处理会出乱码
		String strValue = (String) hmConfig.get(key);
		if (strValue == null || "".equals(strValue)) {
			return "";
		}
		return strValue.trim();
	}

	private boolean isUpdateFile() {
		long lastModify = fileObj.lastModified();
		if (lastModify > lastModifyTime) {
			propertiesUtil.readConfig(false);
			return true;
		}
		return false;
	}

	public static List getPropertiesByKey(String filePath, String key) {
		List cadTypes = new ArrayList();
		try {
			PropertiesUtil pro = new PropertiesUtil(filePath);
			String strEPMTypes = pro.getValueByKey(key);
			String[] arr = strEPMTypes.split(",");
			for (int i = 0; i < arr.length; i++) {
				String s = arr[i];
				if (!cadTypes.contains(s)) {
					cadTypes.add(s);
				}
			}
		} catch (Exception e) {

		}
		return cadTypes;
	}

	/**
	 * 获取RDP的token
	 * @return
	 * @throws JSONException
	 */
	public static String getRDPToken(String configFilePath) throws JSONException {
		PropertiesUtil ut = new PropertiesUtil(configFilePath);
		String erdpUrlHost = ut.getValueByKey("erdp.url");
		String tokenUsername = ut.getValueByKey("erdp.tokenUsername");
		String tokenPassword = ut.getValueByKey("erdp.tokenPassword");
    	String erdpurl = erdpUrlHost +"/tmrdp/v1/auth/token";
		String token="";
		// 1. 创建HttpClient对象
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 2. 创建HttpPost对象
		HttpPost post = new HttpPost(erdpurl);
		// 3. 设置POST请求传递参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("username", tokenUsername));
		params.add(new BasicNameValuePair("password", tokenPassword));
		try {
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		// 4. 执行请求并处理响应
		try {
			CloseableHttpResponse response = httpClient.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null){
				String strrep = EntityUtils.toString(response.getEntity());
				if (strrep != null && !"".equals(strrep)) {
					JSONObject obj = new JSONObject(strrep);
					if (obj.has("access_token")) {
						String access_token = obj.getString("access_token");
						if(access_token != null && !"".equals(access_token)) {
							token = "Bearer "+access_token;
						}
					}
				}

			}
			response.close();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 释放资源
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return token;
	}
}
